package net.forsalemall.android;

import java.util.ArrayList;
import java.util.List;



import org.json.JSONArray;
import org.json.JSONObject;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.droidfu.widgets.WebImageView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.utils.Constants;
import com.utils.HttpUtils;
import com.utils.Utils;

public class AdsBySupCatActivity extends ListActivity {

	private List<ListItem> allItems;
	private List<ListItem> items;
	private EfficientAdapter adap;
	private String adData;
	private JSONArray jAds;
	private int supCatId;
	private int adType;
	private String screenTitle;
	private String countryCode;
	private RelativeLayout searchLayout;
	
	private Action showSearchAction;
	private Action hideSearchAction;
	
	private Button searchButton;
	private TextView searchTextView;
	
	private PullToRefreshListView pullToRefreshListView;
	private int currentPage;

	public void onCreate(Bundle icicle) {
		try {
			super.onCreate(icicle);
			setContentView(R.layout.ads_by_sup_cat);
			countryCode = getIntent()
					.getStringExtra(Constants.KEY_COUNTRY_CODE);
			supCatId = getIntent().getIntExtra(Constants.KEY_SUPER_CATEGORY_ID, -1);
			adType = getIntent().getIntExtra(Constants.KEY_AD_TYPE,
					Constants.TYPE_NORMAL_AD);
			screenTitle = getIntent().getStringExtra(Constants.KEY_SUPER_CATEGORY_NAME);
			pullToRefreshListView = (PullToRefreshListView) findViewById(R.id.pull_refresh_list);
			pullToRefreshListView.setMode(Mode.PULL_UP_TO_REFRESH);
			searchButton = (Button)findViewById(R.id.search_button);
			searchTextView = (TextView)findViewById(R.id.search_field);
			searchLayout = (RelativeLayout)findViewById(R.id.search_layout);
			searchLayout.setVisibility(View.GONE);
			final ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
			showSearchAction = new Action() {
				public void performAction(View view) {
					actionBar.removeAllActions();
					actionBar.addAction(hideSearchAction);
					searchLayout.setVisibility(View.VISIBLE);
				}

				public int getDrawable() {
					return R.drawable.ic_menu_search;
				}
			};
			hideSearchAction = new Action() {
				public void performAction(View view) {
					actionBar.removeAllActions();
					actionBar.addAction(showSearchAction);
					searchLayout.setVisibility(View.GONE);
				}

				public int getDrawable() {
					return R.drawable.ic_menu_search_hide;
				}
			};
			actionBar.setTitle(screenTitle);
			actionBar.setHomeAction(new Action() {

				public void performAction(View view) {
					backToHome();
				}

				public int getDrawable() {
					// TODO Auto-generated method stub
					return R.drawable.ic_title_home_default;
				}
			});
			actionBar.setDisplayHomeAsUpEnabled(true);
//			unFavAction = new Action() {
//				public void performAction(View view) {
//					unfavoriteAds();
//				}
//
//				public int getDrawable() {
//					return R.drawable.ic_menu_unfavorite;
//				}
//			};
			actionBar.addAction(showSearchAction);
//			actionBar.addAction(unFavAction);
			

			allItems = new ArrayList<ListItem>();
			items = new ArrayList<ListItem>();
			
			adap = new EfficientAdapter(AdsBySupCatActivity.this);
			pullToRefreshListView.getRefreshableView().setAdapter(adap);
//			setListAdapter(adap);
			
			searchButton.setOnClickListener(new View.OnClickListener() {				
				public void onClick(View v) {
					filterItems(searchTextView.getText());
				}
			});
			
			pullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
				public void onRefresh(PullToRefreshBase<ListView> refreshView) {
					pullToRefreshListView.setLastUpdatedLabel(DateUtils.formatDateTime(getApplicationContext(),
							System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE
									| DateUtils.FORMAT_ABBREV_ALL));

					// Do work to refresh the list here.					
					new GetDataTask().execute();
				}
			});
			pullToRefreshListView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {
				public void onLastItemVisible() {
									
					
				}
			});
			
			new AsyncTask<String, String, String>() {
				private ProgressDialog progressDialog;

				protected void onPreExecute() {
					try {
						progressDialog = Utils.getProgressDialog(
								AdsBySupCatActivity.this, null,
								getString(R.string.loading));
						progressDialog.show();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				protected String doInBackground(String... arg0) {
					try {
						currentPage = 0;
						loadData();
					} catch (Exception e) {
						e.printStackTrace();
					}
					return null;
				}

				protected void onPostExecute(String unused) {
					try {
						if(allItems.size()<Constants.NUMBER_OF_ROW_PERPAGE*currentPage){
			        		pullToRefreshListView.setMode(Mode.DISABLED);
			        	}
						adap.notifyDataSetChanged();
						progressDialog.dismiss();

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.execute();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void filterItems(CharSequence searchKey){
		try {
			items.clear();
			ListItem lItem;
			searchKey = searchKey.toString().toLowerCase();
			for(int i=0;i<allItems.size();i++){
				lItem = allItems.get(i);
				if(lItem.title.toLowerCase().contains(searchKey)){
					items.add(lItem);
				}
			}
			adap.notifyDataSetChanged();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	private void backToHome() {
		try {
			startActivity(new Intent(this, HomeActivity.class)
					.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	class ListItem {
		boolean isChecked;
		private int adId;
		private int status;
		private String listCatInfo;
		private String title;
		private String url;

		public ListItem(int adId,int status,String listCatInfo, String title, String url) {
			this.adId = adId;
			this.status = status;
			this.listCatInfo = listCatInfo;
			this.title = title;
			this.url = url;
			this.isChecked = false;
		}
	}

	public class EfficientAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		private Context context;

		public EfficientAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
			this.context = context;
		}

		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(
						R.layout.ads_by_sup_cat_list_content, null);
				holder = new ViewHolder();
				holder.icon = (WebImageView) convertView
						.findViewById(R.id.list_icon);
				holder.listCatInfo = (TextView) convertView
				.findViewById(R.id.list_cat_info);
				holder.title = (TextView) convertView
						.findViewById(R.id.list_title);
				holder.soldView  = (ImageView) convertView
				.findViewById(R.id.sold_icon);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			if (position % 2 == 0) {
				convertView.setBackgroundColor(Constants.BG_EVEN_CELL);
			} else {
				convertView.setBackgroundColor(Constants.BG_ODD_CELL);
			}
			if(items.get(position).status==Constants.AD_STATUS_SOLD){
				holder.soldView.setVisibility(View.VISIBLE);
			}else{
				holder.soldView.setVisibility(View.GONE);
			}
			holder.icon.setImageUrl(items.get(position).url);
			holder.icon.loadImage();
			holder.listCatInfo.setText(items.get(position).listCatInfo); 
			holder.title.setText(items.get(position).title);
			convertView.setOnClickListener(new AdClickListener(items
					.get(position)));
			return convertView;
		}

		class ViewHolder {
			WebImageView icon;
			TextView listCatInfo;
			TextView title;
			ImageView soldView;
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return items.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return items.get(position);
		}
	}


	public class AdClickListener implements OnClickListener {
		private ListItem listItem;

		public AdClickListener(ListItem listItem) {
			this.listItem = listItem;
		}

		public void onClick(View v) {
			try {
				Intent intent = new Intent(AdsBySupCatActivity.this,
						AdDetailsActivity.class);
				intent.putExtra(Constants.KEY_COUNTRY_CODE, getIntent()
						.getStringExtra(Constants.KEY_COUNTRY_CODE));
				intent.putExtra(Constants.KEY_AD_ID, listItem.adId);
				intent.putExtra(Constants.KEY_AD_TEXT, listItem.title);
				intent.putExtra(Constants.KEY_IS_SOLD,(listItem.status == Constants.AD_STATUS_SOLD));
				intent.putExtra(Constants.KEY_IS_FROM_MY_APP,false);
				startActivity(intent);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	private void loadData(){
		try {
			adData = HttpUtils.getLimitSearchSupCatAds(adType,supCatId,countryCode,currentPage*Constants.NUMBER_OF_ROW_PERPAGE,Constants.NUMBER_OF_ROW_PERPAGE);					
			jAds = new JSONArray(adData);
			if (jAds != null) {
				currentPage++;
				JSONObject jo;
				ListItem lItem;
				String fileName;
				String supCatAndCatInfo;
				for (int i = 0; i < jAds.length(); i++) {
					jo = jAds.getJSONObject(i);
					fileName = jo.getString("img_file_name");
					supCatAndCatInfo = Utils.getDecodedString(jo
									.getString("cat_name"));
					if(fileName!= null && fileName.length()>3){
						lItem = new ListItem(jo.getInt("ad_id"), jo.getInt("stat"),
								supCatAndCatInfo,
								Utils.getDecodedString(jo
								.getString("text")), HttpUtils
								.getFileUrl(Constants.getAdImgThumbDirName(),fileName));
					}else{
						lItem = new ListItem(jo.getInt("ad_id"), jo.getInt("stat"),
								supCatAndCatInfo,
								Utils.getDecodedString(jo
								.getString("text")), HttpUtils
								.getFileUrl(Constants.getDefaultImgDirName(),
										Constants.getDefaultImgFileName()));
					}
					
					allItems.add(lItem);
					items.add(lItem);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private class GetDataTask extends AsyncTask<String, String, String> { 
		 
        protected String doInBackground(String ... params) {
        	loadData();
            return null;
        }
 
        protected void onPostExecute(String unused) {
        	adap.notifyDataSetChanged();
//        	pullToRefreshListView.
        	pullToRefreshListView.onRefreshComplete();
        	if((allItems.size()>=100)||(allItems.size()<Constants.NUMBER_OF_ROW_PERPAGE*currentPage)){
        		pullToRefreshListView.setMode(Mode.DISABLED);
        	}
        }
    }
}